<?php

class SJB_Admin_Users_AddUser extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('manage_users');
		return parent::isAccessible();
	}

	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();
		$user_group_id = SJB_Request::getVar('user_group_id', null);

		if (is_null($user_group_id)) {
			$user_groups_info = SJB_UserGroupManager::getAllUserGroupsInfo();
			$tp->assign('user_groups_info', $user_groups_info);
			$tp->display('add_user_choose_user_group.tpl');
		} else {
			$user_group_sid = SJB_UserGroupManager::getUserGroupSIDByID($user_group_id);
			$user_group_info = SJB_UserGroupManager::getUserGroupInfoBySID($user_group_sid);
			$user = SJB_ObjectMother::createUser($_REQUEST, $user_group_sid);
			$user->deleteProperty('active');
			$registration_form = SJB_ObjectMother::createForm($user);
			$registration_form->registerTags($tp);
			$form_submitted = SJB_Request::getVar('action', '') == 'add';
			$errors = array();

			if (SJB_UserGroupManager::isUserEmailAsUsernameInUserGroup($user_group_sid) && $form_submitted) {
				$email = $user->getPropertyValue('email');
				if (is_array($email))
					$email = $email['original'];
				$user->setPropertyValue('username', $email);
			}

			if ($form_submitted && $registration_form->isDataValid($errors)) {
				SJB_UserManager::saveUser($user);
				SJB_UserManager::activateUserByUserName($user->getUserName());
				$defaultProduct = SJB_UserGroupManager::getDefaultProduct($user_group_sid);
				if ($defaultProduct) {
					$contract = new SJB_Contract(array('product_sid' => $defaultProduct));
					$contract->setUserSID($user->getSID());
					$contract->saveInDB();
				}
				SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/users/");
			}
			else {
				if (SJB_UserGroupManager::isUserEmailAsUsernameInUserGroup($user_group_sid))
					$user->deleteProperty('username');
				$registration_form = SJB_ObjectMother::createForm($user);
				$registration_form->registerTags($tp);
				$tp->assign("errors", $errors);
				$tp->assign("user_group", $user_group_info);
				$tp->assign("form_fields", $registration_form->getFormFieldsInfo());
				$tp->display("add_user.tpl");
			}
		}
	}
}
